package com.gzsxy.esjy.service.file.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzsxy.esjy.common.base.exception.impl.BusinessException;
import com.gzsxy.esjy.common.base.exception.impl.CustomAssert;
import com.gzsxy.esjy.common.base.result.R;
import com.gzsxy.esjy.common.base.result.ResultCodeEnum;
import com.gzsxy.esjy.common.base.util.FileUtils;
import com.gzsxy.esjy.service.base.handler.GuliEception;
import com.gzsxy.esjy.service.file.configure.FileProperties;
import com.gzsxy.esjy.service.file.dao.FileMapper;
import com.gzsxy.esjy.service.file.entity.FileResource;
import com.gzsxy.esjy.service.file.entity.dto.UploadDto;
import com.gzsxy.esjy.service.file.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 文件服务
 * @date 2021/12/21 14:46
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileResource> implements FileService {

    private static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);

    private static final String A = ".";

//    @Value("${server.system_id}")
//    private String system_id;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileProperties fileProperties;

    /**
     * @description: 文件上传
     * @param file 文件
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public FileResource upload(MultipartFile file) {
        try {
            //文件原名称
            String filename = file.getOriginalFilename();
            //文件无后缀
            CustomAssert.notTrue(filename.lastIndexOf(A) != -1, ResultCodeEnum.FILE_EXTENSION_ERROR.getMessage());
            // 获取文件后缀
            String extension = filename.substring(filename.lastIndexOf(A));
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +
                    UUID.randomUUID().toString().replace("-", "") + extension;

//            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            //获取jar包同级目录(jar下无法生成目录)
//            String realPath = ResourceUtils.getURL("classpath:").getPath();
            //获取当前项目路径
            String realPath = System.getProperty("user.dir")+File.separator;
            String catalogue = realPath + fileProperties.getUploadPath();
            System.out.println(catalogue);
            //创建目录
            boolean ismkdir = FileUtils.mkdir(catalogue);
            if (ismkdir){
                //上传
                file.transferTo(new File(catalogue,newFileName));
                //插入表
                FileResource fileResource = new FileResource();
                fileResource.setFileName(newFileName);
                fileResource.setFileIndex(fileProperties.getSystem_id() + File.separator +newFileName);
                fileResource.setFilePath(catalogue + File.separator +newFileName);
                fileResource.setSystemId(fileProperties.getSystem_id());
                fileResource.setFileSize(file.getSize());
                fileMapper.insert(fileResource);
                return fileResource;
            }else {
                  //抛出文件目录创建错误
                  CustomAssert.notTrue(ismkdir,ResultCodeEnum.FILE_CATALOGUE_ERROR.getMessage());
                  return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            //抛出文件上传错误
           throw new GuliEception(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * @description: 删除文件
     * @param fileIndex 索引
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(String fileIndex) {
        LambdaQueryWrapper<FileResource> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(FileResource::getFileIndex,fileIndex);
        FileResource fileResource = fileMapper.selectOne(wrapper);
        //文件不存在或已删除
        CustomAssert.notTrue(ObjectUtils.isNotEmpty(fileResource),ResultCodeEnum.FILE_EXIST_ERROR.getMessage());
        String filePath = fileResource.getFilePath();
        //获取文件名
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
        File file = new File(filePath);
        boolean success = file.delete();
        if (success){
            //删除文件数据
            fileMapper.deleteById(fileResource.getId());
        } else {
            log.error("文件名为:[{}]删除失败",fileName);
        }
    }


    /**
     * @description: 上传base64文件
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public FileResource uploadBase64(UploadDto uploadDto) throws Exception {
        String content = uploadDto.getContent();
        String fileType = uploadDto.getFileType();
        if (fileType.startsWith(".")){
            fileType = fileType.substring(1);
        }
        int b = content.indexOf("base64,");
        if (b>=0){
            content = content.substring(b+"base64,".length());
        }
        byte[] decode = Base64.getMimeDecoder().decode(content);
        FileResource fileResource = new FileResource();
        String name = UUID.randomUUID().toString();
        String fileName = null;
        if (!StringUtils.isEmpty(uploadDto.getIndex())){
            fileName = uploadDto.getIndex();
            if (fileName.startsWith(fileProperties.getSystem_id()+"/")){
                fileName = fileName.replace(fileProperties.getSystem_id()+"/","");
            }
            name = fileName;
        } else {
            fileName = name + "." + fileType;
        }
        String realPath = System.getProperty("user.dir")+File.separator;
        String catalogue = realPath + fileProperties.getUploadPath();
        fileResource.setSystemId(fileProperties.getSystem_id());
        fileResource.setFileName(fileName);
        fileResource.setFilePath(catalogue + File.separator +fileName);
        fileResource.setFileSize((long)decode.length);
        fileResource.setFileIndex(fileProperties.getSystem_id() + File.separator +fileName);
        fileMapper.insert(fileResource);
        FileUtils.createFileOfByte(decode,catalogue + File.separator+fileName);
        log.info("文件上传成功{}",catalogue + File.separator+fileName);
        return fileResource;
    }
}
